import axios from "axios";
import { getToken, clearToken } from "./token";
import router from "@/router";

const http = axios.create({
  baseURL: "https://mock.mengxuegu.com/mock/6881c906eb21615e5196dd1d/api",
  timeout: 5000,
});

//添加请求拦截器
http.interceptors.request.use((config) => {
  const token = getToken();
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

//添加拦截器
http.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    console.dir(error);
    if (error.response.status === 401) {
      clearToken();
      router.navigate("/login");
      window.location.reload();
    }
    return Promise.reject(error);
  }
);
export { http };
